package com.dhy.socket;

import com.dhy.socket.request.core.HttpRequestInHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 大忽悠
 * @create 2022/6/20 17:05
 */
@Slf4j
public class DZServer {

    public static void start(){
        NioEventLoopGroup boss=null;
        NioEventLoopGroup worker=null;
        Channel serverCh=null;
        try {
             boss = new NioEventLoopGroup(1);
             worker = new NioEventLoopGroup();
             serverCh = new ServerBootstrap().group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //设置日志级别
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            //添加http协议解析器
                            ch.pipeline().addLast(new HttpServerCodec());
                            ch.pipeline().addLast(new HttpRequestInHandler());
                        }
                    }).bind(80).
                    //同步阻塞
                    sync().channel();
                    //同步阻塞等待结束
                    serverCh.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("服务器启动异常: ",e);
        }finally {
            if(boss!=null){
                boss.shutdownGracefully();
            }
            if(worker!=null){
                worker.shutdownGracefully();
            }
        }
    }
}
